package com.bob.light.config

import com.bob.light.TuyaHomeSDKHelper
import com.tuya.smart.sdk.bean.DeviceBean

object DeviceConfig {

    private var deviceBeanList: MutableList<DeviceBean> = mutableListOf()

    fun save(deviceBean: DeviceBean?) {
        deviceBean?.let {
            saveToMemory(deviceBean)
        }
    }

    fun queryDeviceList(): MutableList<DeviceBean> {
        if (deviceBeanList.isNotEmpty()) {
            return deviceBeanList
        }
        TuyaHomeSDKHelper.queryFamilyList { homeList ->
            homeList?.forEach { home ->
                TuyaHomeSDKHelper.queryFamilyDetail(home.homeId) {homeDetail ->
                    if (homeDetail?.deviceList?.isNotEmpty() == true) {
                        deviceBeanList.addAll(homeDetail.deviceList)
                    }
                }
            }
        }
        return deviceBeanList
    }

    private fun saveToMemory(deviceBean: DeviceBean) {
        var flag = false
        this.deviceBeanList.forEach {
            if (it.devId == deviceBean.devId) {
                flag = true
                return@forEach
            }
        }
        if (!flag) {
            this.deviceBeanList.add(deviceBean)
        }
    }
}